import redis
from flask import Flask
from flask_session import Session
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import CSRFProtect
from flask_wtf.csrf import generate_csrf

from config import config
from info.common import do_index_class


db = SQLAlchemy()
redis_store = None


def current_app(config_name):
    # 设置日志
    app = Flask(__name__)
    app.config.from_object(config["config"])
    db.init_app(app)
    # 创建Redis对象与Redis服务器连接
    global redis_store
    redis_store = redis.StrictRedis(host=config[config_name].REDIS_HOST, port=config[config_name].REDIS_PORT, decode_responses=True)
    # 只做校验 校验cookie中的csrf_token和表单中的cdrf_token的值
    CSRFProtect(app)
    # 自定义过滤器
    app.add_template_filter(do_index_class, "index_class")
    # 每次视图函数请求时,获取响应,添加csrf_token
    @app.after_request
    def after_response(response):
        csrf_token = generate_csrf()
        response.set_cookie("csrf_token", csrf_token)
        return response
    Session(app)
    from info.modules.index import index_blu
    from info.modules.passport import login_blu
    from info.modules.news import news_blu
    from info.modules.profile import profile_blu
    from info.modules.admin import admin_blu
    app.register_blueprint(index_blu)
    app.register_blueprint(login_blu)
    app.register_blueprint(news_blu)
    app.register_blueprint(profile_blu)
    app.register_blueprint(admin_blu)
    return app